<?php

namespace app\admin\controller;
header('Access-Control-Allow-Origin:*');//允许所有来源访问
header('Access-Control-Allow-Method:POST,GET');//允许访问的方式
use think\Controller;
use app\admin\model\AuthRule;
use think\Db;
use OSS\OssClient;
use OSS\Core\OssException;

class Base extends Controller
{
    protected $_btw = [0, 0]; // 时间区间等
    protected $_map = []; //get参数
    protected $_p = 1; //分页页数
    protected $_order = ""; //排序
    protected $_row = 10; //每页条数
    protected $_user = []; //登录对象
    protected $_param = []; //post参数及get参数
    protected $_model = []; //模型对象
    protected $_type = false; //是否是_edit
    protected $_config = []; //系统配置
    protected $uid = 1;
    protected $url='';
    protected $accessKeyId='LTAIC0Yv1Jbu5x7v';
    protected $accessKeySecret='1OSGmCsAhh6Dwe9ZRQzc54wIDZskdk';
    protected $bucket='lctx';
    protected $endpoint = "oss-cn-beijing.aliyuncs.com";

    public function _initialize()
    {
        $this->_user = is_login();
        empty($this->_user) && $this->redirect("Admin/login");
        $this->uid = $this->_user['id'];
        /*     $this->_user['is_root'] = is_administrator($this->uid);
             define('IS_ROOT', $this->_user['is_root']); */
        $this->_getmenu(); //获取菜单
        $this->_getdata();
        $this->_param = $this->request->param();
        $this->admin_name();
        $this->assign('system_name', '箭向');
        $this->assign('empty', '<tr><td colspan="20" style="text-align:center;">暂无数据!</td></tr>');
        $this->url ='http://img.lctx.xdjst.com';
    }

    public function uploads_file($type)
    {
        $path = '/uploads/headimg/';
        switch ($type) {
            case 1:
                $path = '/uploads/headimg/';
                break;//头像
            case 2:
                $path = '/uploads/card/';
                break;//身份证
            case 3:
                $path = '/uploads/subject/';
                break;//主题
            case 4:
                $path = '/uploads/teasure/';
                break;//鉴宝
            case 5:
                $path = '/uploads/goods/';
                break;//产品发布
            case 6:
                $path = '/uploads/expert/';
                break;//专家
            case 7:
                $path = '/uploads/banner/';
                break;//banner
        }
//        $log = "<br />".json_encode($_POST);
//        @file_put_contents('uploads/alipay.html', $log, FILE_APPEND);
        if (!empty($_FILES['uploadkey'])) {
            $new_dir = isset($new_dir) ? $new_dir : $_SERVER['DOCUMENT_ROOT'] . $path;
            if (!file_exists($new_dir)) {
                $this->createDir($new_dir);
            }

            $fs = array();
            $result = 0;
            foreach ($_FILES as $name => $file) {

                $file_types = explode(".", $file['name']);
                $file_type = $file_types [count($file_types) - 1];
                $fn = substr(md5(rand(1, time())), rand(0, 8), 20) . $this->param['uid'] . '.' . $file_type;
                $ft = strrpos($fn, '.', 0);
                $fm = substr($fn, 0, $ft);
                $fe = substr($fn, $ft);
                $fp = $_SERVER['DOCUMENT_ROOT'] . $path . $fn;
                $fi = 1;

                if (!in_array(strtolower($file_type), array('gif', 'png', 'jpg', 'jpeg'))) {
                    $fs[$name]['code'] = 201;
                    $fs[$name]['msg'] = '文件格式不对';
                }

                while (file_exists($fp)) {
                    $fn = $fm . '[' . $fi . ']' . $fe;
                    $fp = $_SERVER['DOCUMENT_ROOT'] . $path . $fn;;
                    $fi++;
                }

                $result = move_uploaded_file($file['tmp_name'], $fp);
                $code = 201;
                if ($result) $code = 200;

                $fs[$name] = array('name' => $fn, 'url' => $fp, 'type' => $file['type'], 'size' => $file['size'], 'code' => $code);
            }

            if ($result) {
                $fs['uploadkey']['code'] = 200;
                $fs['uploadkey']['msg'] = '上传成功';
                return $fs;
            } else {
                $fs['uploadkey']['code'] = 201;
                $fs['uploadkey']['msg'] = '上传失败';
                return $fs;
            }

        }
    }

    function createDir($path)
    {
        if (!file_exists($path)) {
            $this->createDir(dirname($path));
            @mkdir($path, 0777);
        }
    }

    //管理员姓名
    public function admin_name()
    {
        $info = db('manager')->where(['id' => $this->uid])->find();
        $Administrator = $info['username'];
        $this->assign('Administrator', $Administrator);
    }

    /**
     * get参数初始化
     */
    private function _getdata()
    {
        //获取兼容路由参数
        $getdata = array_merge($this->request->get(), $this->request->route());

        foreach ($getdata as $k => $v) {
            is_string($v) && $v = trim($v);
            if (trim($v) == '') {
                continue;
            }
            switch ($k) {
                case "order":
                    strpos($v, "-") > -1 ? $v = str_replace("-", " ", $v) : $v = $v . " desc";
                    $this->_order = $v;
                    break;
                case 'title':
                case 'name':
                case 'description':
                case 'nickname':
                case 'id':
                case 'uid':
                case 'p_uid':
                case 'mobile':
                case 'order_sn':
                case 'sn':
                case 'real_name':
                case 'content':
                case 'tel':
                    $this->_map[$k] = array('like', '%' . $v . '%');
                    break;
                case 'vip_level':
                    $this->_map[$k] = $v;
                    break;
                case 'category_id':
                    $this->_map[$k] = $v;
                    break;
                case 'status':
                    $this->_map[$k] = $v;
                    break;
                case 'expert_auth':
                    $this->_map[$k] = $v;
                    break;
                case 'identity_auth':
                    $this->_map[$k] = $v;
                    break;
                case 'expert_uid':
                    $this->_map[$k] = $v;
                    break;
                case 'type':
                    if ($v != 0) $this->_map[$k] = $v;
                    break;
                case 'm_mobile':
                    $this->_map['m.mobile'] = array('like', '%' . $v . '%');
                    break;
                case 'e_name':
                    $this->_map['mxkj_expert.name'] = array('like', '%' . $v . '%');
                    break;
                case "s_time":
                    $this->_btw[0] = strtotime($v);
                    $this->_btw[1] = time();
                    $this->_map['reg_time'] = ['between', $this->_btw];
                    break;
                case "e_time":
                    $this->_btw[1] = strtotime($v);
                    $this->_map['reg_time'] = ['between', $this->_btw];
                    break;
                case "s_time2":
                    $this->_btw[0] = strtotime($v);
                    $this->_btw[1] = time();
                    $this->_map['create_time'] = ['between', $this->_btw];
                    break;
                case "e_time2":
                    $this->_btw[1] = strtotime($v);
                    $this->_map['create_time'] = ['between', $this->_btw];
                    break;
                case 'pid':
                    $this->_map[$k] = $v;
                    break;
                case "p":
                    $this->_p = $v;
                    break;
                case "row":
                    $this->_row = $v;
                    break;
                case "searchkey":
                    break;
                case "order_status":
                    $this->_map['o.status'] = $v;
                    break;
                case "debug":
                    defined("DEBUG") || define("DEBUG", $v);
                    break;
                case 'nickname':
                    $this->_map[$k] = $v;
                    break;
                /* case startWith($k, "search"):
                    $this->_map[str_replace("search_", "", $k)] = array("like", "%" . $v . "%");
                    break;
                case startWith($k, "stime"):
                    $this->_btw[0]                             = strtotime($v);
                    $this->_btw[1]                             = time();
                    $this->_map[str_replace("stime_", "", $k)] = ['between', $this->_btw];
                    break;
                case startWith($k, "etime"):
                    $this->_btw[1]                             = strtotime($v) + 3600 * 24;
                    $this->_map[str_replace("etime_", "", $k)] = ['between', $this->_btw];
                    break; */
                default:
                    //$this->_map[$k] = $v;
                    break;
            }
        }

    }

    /**
     * 菜单权限
     */
    private function _getmenu()
    {
        header("Content-type:text/html;charset=utf-8");
        $role = $this->_getrole();
        $menu_arr = (new AuthRule())->role($role);
        $menu = [];
        if ($role == 'all') {
            $menu = $menu_arr;
        } else {
            foreach ($menu_arr as $k => $v) {
                foreach ($v['sub'] as $ka => $va) {
                    if (strpos($role, ',' . $va['id'] . ',') > -1) {
                        $menu[$k]['sub'][$ka] = $va;
                        $menu[$k]['title'] = $v['title'];
                        $menu[$k]['name'] = $v['name'];
                        $menu[$k]['icon'] = $v['icon'];
                        $menu[$k]['pid'] = $v['pid'];
                        $menu[$k]['id'] = $v['id'];
                        $menu[$k]['checked'] = $v['checked'];
                    }
                }
            }
        }
        //print_r($role);die;
        /* db('auth_rule')->select();
        
        $menu = [];
        if(!empty($role)){
            $role = explode(',',$role);//print_r($role);die;
            foreach ($menu_arr as $k=>$v){
                
               foreach ($v['sub'] as $ka=>$va){
                   if(strpos($rule, ',' . $value['id'] . ',') > -1){
                       $menu[$k]['child'][$ka] = $va;
                       $menu[$k]['name'] = $v['name'];
                       $menu[$k]['icon'] = $v['icon'];
                   }
               }
            }
        }else{
            $this->error('操作非法', '');
        } */
        //print_r($menu);die;
        $this->assign("menu", $menu);
    }

    protected function _getrole()
    {
        $info = db('manager')->where(['id' => $this->uid])->find();
        if ($info) {
            $role = Db::name('auth_group')->where(['id' => $info['role']])->value('rules');
            return $role;
        }
        return false;
    }

    /**
     * 得到子级数组
     * @author fenghao <303529990@qq.com>
     * date 2016-12-23 13:00
     * @param int
     * @return array
     */
    private function _get_child($myid, $arr)
    {
        $newarr = array();
        foreach ($arr as $k => $v) {
            $v['name'] = $v['module'] . "/" . $v['name'];
            if ($v['pid'] == $myid && (IS_ROOT || $this->_checkRule(strtolower($v['name']), $v['type']))) {
                $newarr[$k] = $v;
            }
        }
        return $newarr ? $newarr : false;
    }

    private function _get_childs($myid, $arr)
    {
        $newarr = array();
        foreach ($arr as $k => $v) {
            $v['name'] = $v['module'] . "/" . $v['name'];
            if ($v['pid'] == $myid) {
                $newarr[$k] = $v;
            }
        }
        return $newarr ? $newarr : false;
    }

//获取细化权限
    private function _get_childss()
    {
        if (substr_count($this->request->url(), '/') > 3) {
            $res = explode('/', $this->request->url());
            if (isset($res)) {
                $data = strtolower($res[2] . '/' . $res[3]);
                $info = (new Manager())->where(['id' => $this->uid])->find();
                $menu_m = db('auth_group')->where(['id' => $info['role']])->find();
                $menu_ml = explode(',', $menu_m['rules']);
                $menu_d = db('auth_rule')->select();
                foreach ($menu_d as $k => $v) {
                    if (in_array($v['id'], $menu_ml)) {
                        $menulist[] = $menu_d[$k];
                    }
                }
                $sort = new VStore();
                $menulist = $sort->Rsort($menulist, 'sort');//排序
                foreach ($menulist as $km => $vm) {
                    $list[] = strtolower($vm['name']);
                }
                if (in_array($data, $list) == false) {
                    $this->error('您没有权限访问');
                }
            }
        }

    }

    /**
     * 权限检测
     * @param string $rule 检测的规则
     * @param string $mode check模式
     * @return boolean
     * @author 朱亚杰  <xcoolcc@gmail.com>
     */
    protected function _checkRule($rule, $type, $mode = 'url')
    {
        static $Auth = null;
        if (!$Auth) {
            $Auth = new Auth();
        }
        if (!$Auth->check($rule, $this->uid, $type, $mode)) {
            return false;
        }
        return true;
    }

    /**
     * 初始化模型
     * @param type $fun
     */
    final protected function initModel()
    {
        $fun = strtolower($this->request->action());
        if (strpos($fun, '_edit') > -1 || strpos($fun, '_add') > -1) {
            $fun = str_replace('_edit', '', $fun);
            $fun = str_replace('_add', '', $fun);
            $this->_type = true;
        }
        $this->_model = Model::get(['alias' => $fun]);
        if ($this->_model) {
            $this->_param['mid'] = $this->_model['id'];
            $this->_map['mid'] = $this->_model['id'];
            $this->assign('model', $this->_model);
        }
    }

    public function _empty()
    {
        $this->redirect('Index/index');
    }

    public function ajaxReturn($msg = '', $data = '', $total = 0, $code = 0)
    {
        echo json_encode(array('code' => $code, 'msg' => $msg, 'count' => $total, 'data' => $data));
        exit;
    }

    public function vip_level()
    {
        return array(
            '1' => '银钻', '2' => '金钻', '0' => '普通VIP',
        );
    }

    public function pointType()
    {
        return array(
            '1' => '转入', '2' => '转出', '3' => '兑换', '4' => '买入', '5' => '卖出', '6' => '签到', '7' => '系统充值',
        );
    }

    public function balanceType()
    {
        return array(
            '1' => '注册赠送', '2' => '充值创始资产', '3' => '充值配置资产', '4' => '充值赠送资产',
            '5' => '提现到交易所', '6' => '转入', '7' => '转出',
            '8' => '提现审核未通过退还', '10' => '创始资产每日释放', '11' => '配置资产每日释放',
            '12' => '加速奖励', '20' => '创始资产转入区块发送', '21' => '配置资产转入区块发送', '22' => '赠送资产转入区块发送',
        );
    }

    public function state()
    {
        return array(
            '0' => '待付款',
            '1' => '待确认',
            '2' => '已完成',
            '-1' => '已关闭'

        );
    }

    public function jiaobao()
    {
        return array(
            '0' => '待付款',
            '1' => '预约中',
            '2' => '已预约',
            '3' => '已完成',
            '-1' => '取消',
            '-2' => '已删除'

        );
    }

    public function onjianbao()
    {

        return array(
            '0' => '待付款',
            '1' => '鉴定中',
            '2' => '鉴定完成',
            '-1' => '取消',
            '-2' => '已删除'
        );
    }

    public function jieguyo()
    {
        return [
            '1' => '真品',
            '0' => '赝品'
        ];
    }


    public function pay_type()
    {
        return array(
            '1' => '首页顶部',
            '2' => '首页中部',
            '3' => '商城顶部banner',
            '4' => '商城中部banner'
        );
    }

    //商品订单详情 状态
    public function order_statue()
    {
        return [
            '0' => '待付款',
            '1' => '已付款/待发货',
            '2' => '已发货/待收货',
            '3' => '已完成',
            '-1' => '取消订单',
            '-2' => '订单失效',
            '-3' => '删除订单'
        ];
    }

    //商品列表 状态
    public function goods_status()
    {
        return [
            '0' => '下架',
            '1' => '上架',
            '-1' => '审核中',
            '-2' => '审核失败',
            '-3' =>'删除'
        ];
    }
    //专家认证状态
    public function expert_auth(){
        return[
            '1'=> '专家',
            '0'=>'普通用户',
            '-1'=>'认证失败',
            '2'=>'认证中'
        ];
    }
    public function identity_auth(){
        return [
            '2'=>'认证中',
            '1'=>'通过认证',
            '0'=>'未认证',
            '-1'=>'认证失败'
        ];
    }


    /**
     * 通用数据输出
     * @param type $msg 输出提示信息
     * @param type $code 状态码
     * @param type $data 返回数组
     * @param type $result_code 业务逻辑码 不指定默认和状态码一致
     * @param type $type 返回数据格式
     * @return type
     */
    protected function response($msg, $code = 200, $data = '', $result_code = null, $type = 'json')
    {
        $result_code === null && $result_code = $code;
        $result = [
            'code' => $result_code,
            'msg' => $msg,
            'data' => $this->_extents($data),
        ];
        $this->setHeader('X_End_Time', $this->request->time());
        $response = Response::create($result, $type)->code($code)->header($this->header);
        throw new \think\exception\HttpResponseException($response);
    }
}
